package io.gitee.caoxiaoyu97.log.sensitive.pattern;


import io.gitee.caoxiaoyu97.log.sensitive.util.KeywordExpEnum;

import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author caoxiaoyu
 */
public class RegExpConverter implements BaseConverter {
	
	protected String converterCanRun = "true";
	private Integer maxLength = 2048;
	private Pattern jsonPattern = Pattern.compile("^\\s*(\\{.*?\\}|\\[.*?\\])\\s*$");
	
	RegExpConverter(String converterCanRun,Integer maxLength){
		this.converterCanRun  = converterCanRun;
		this.maxLength = maxLength;
	}

    /**
     * 关闭正则匹配，会降低效率
     * @return
     */
	@Override
	public boolean canConverter() {
    	return false;
    }
    
    @Override 
    public String convert(String oriLogMsg) {
        if (oriLogMsg == null || oriLogMsg.isEmpty() || jsonPattern.matcher(oriLogMsg).matches()) {
            return oriLogMsg;
        }
        //如果超长截取
        if (oriLogMsg.length() > maxLength) {
            //后面增加三个终止符
            oriLogMsg = oriLogMsg.substring(0, maxLength) + "<<<";
        }
        return invokeMsg(oriLogMsg);
    }

    public String invokeMsg(final String oriMsg){
        String tempMsg = oriMsg;
        try {
        	for(KeywordExpEnum c : KeywordExpEnum.values()) {
        		if(!c.isAvailable()) {
                    continue;
                }
        		Matcher matcher = c.getMatcher(tempMsg);
        		StringBuffer sb = new StringBuffer();
        		while (matcher.find()) {
                    String original = matcher.group();
                    if (!Objects.isNull(original)) {
                        matcher.appendReplacement(sb, SensitiveDataConverter.facade(original, c.getKeywordType()));
                    }
                }
                if (sb.length() != 0) {
                    matcher.appendTail(sb);
                    tempMsg = sb.toString();
                }
        	}
        	
        } catch (Exception e) {
            return tempMsg;
        }
        return tempMsg;
    }
    
}
